<template>
  <div class="departmentListContainer">
    <van-sticky>
      <van-row>
        <van-col span="24">
          <van-search v-model="value" placeholder="请输入搜索科室名称"/>
        </van-col>
      </van-row>
    </van-sticky>

    <van-loading v-if="isLoad" />

    <div  v-else-if="isRead" class="treeContainer">
      <div class="tcLeft">
        <van-sidebar v-model="active" class="departmentSidebar">
          <van-sidebar-item v-for="department in departments" :key="department.departId" :title="department.dname"
                            @click="onClickParent(department)"/>
        </van-sidebar>
      </div>
      <div class="tcRight">
        <van-cell-group class="childDepartmentCellGroup">
          <van-cell is-link v-for="department in departmentsChild" :key="department.departId"
                    :title="department.dname" @click="onClickDepart(department)"></van-cell>
        </van-cell-group>
      </div>
    </div>

    <!-- 网络错误 -->
    <van-empty v-else image="network" description="网络错误！" />

  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {DepartService} from "@/api/api";
import router from "@/router";

const active = ref(0);
const value = ref('');

const departments = ref([]);
const departmentsChild = ref([]);
const isLoad = ref(true);
const isRead = ref(false);

const initial = async () => {
  try {
    // 发送HTTP请求获取后端响应数据
    const response = await DepartService.AllParentList();
    departments.value = response.data;
    await onClickParent(departments.value[0]);
    isLoad.value = false;
    isRead.value = true;
  } catch (error) {
    isLoad.value = false;
    console.error(error);
  }
};

const onClickParent = async (parentDepartment) => {
  try {
    // 发送HTTP请求获取后端响应数据
    const response = await DepartService.childList(parentDepartment.departId);
    departmentsChild.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

const onClickDepart = async (parentDepartment) => {
  try {
    const data = {
      departId: parentDepartment.departId
    };

    await router.push({
      path: '/ShowAppointment',
      state: data
    });
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  initial();
});
</script>


<style scoped>
.departmentListContainer {
  background: white;
}

.departmentSidebar {
  --van-sidebar-background: rgb(245, 247, 250);
  --van-sidebar-width: 37.5vw;
  --van-sidebar-font-size: var(--van-font-size-lg);
  --van-sidebar-line-height: 30px;
}

.childDepartmentCellGroup {
  width: 62.5vw;
  --van-cell-line-height: 40px;
  --van-cell-border-color: rgb(199, 200, 203);
}

.treeContainer {
  display: flex;
}

.treeContainer .tcLeft {

}

.treeContainer .tcRight {

}
</style>